package ngat.oss.simulation.metrics;

import ngat.oss.simulation.*;

import ngat.util.*;
import ngat.phase2.*;
import ngat.astrometry.*;
import ngat.util.logging.*;

import java.util.*;

public class TargetDemandUtilityCalculator implements UtilityCalculator {

	/** Timing constraints window calculator. */
	private TimingConstraintWindowCalculator tcwc;

	/** Exec timing and feasibility model. */
	private ExecutionTimingModel execModel;

	/** Logging. */
	private LogProxy logger;

	/**
	 * Create an OptimalAirmassUtilityCalculator using the supplied models and
	 * time step.
	 */
	public TargetDemandUtilityCalculator(TimingConstraintWindowCalculator tcwc,
			ExecutionTimingModel execModel) {

		this.tcwc = tcwc;
		this.execModel = execModel;

		Logger slogger = LogManager.getLogger("SIM");
		logger = new LogProxy("TDC", "", slogger);

	}

	/** Return the utility for the specified group at time under env. */
	public double getUtility(Group group, long time, EnvironmentSnapshot env,
			ExecutionStatistics hist) {

		// here we use the TCWC to determine the group's demand for the current
		// window to see if we are getting
		// high demand groups selected or not.

		// work out which window this is for the group using the TCWC
		TimeWindow window = tcwc.getWindow(group, hist, time);
		// System.err.println("TDUC: Calc util group:
		// "+group.getClass().getName()+"/"+group.getName()+" at:
		// "+ScheduleSimulator.sdf.format(new Date(time))+
		// " window: "+window);
		// need to limit the window to ? 30 days
		window.start = Math.max(window.start, time);
		window.end = Math.min(window.end, time + 30 * 24 * 3600 * 1000L);
		long rt = tcwc.calculateRemainingTime(group, window, time, env, hist);
		long xt = execModel.getExecTime(group);
		// System.err.println("TDUC: XT="+(xt/1000)+"s RT="+(rt/1000)+"s");

		double demand = (double) xt / ((double) xt + (double) (rt));

		return demand;

	}

}
